import Axios from "axios"
import router from '../router/index.js'
import {
  Loading
} from 'element-ui'
import {
  Message
} from 'element-ui'

Axios.defaults.withCredentials = false; //让ajax携带cookie

// Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Axios.defaults.baseURL = baseUrls;

let loadingInstance;

export default {
  $ajax(apiUrl, data, type, hideLoading) {
    // data = deleteNullProperty(data);

    if (!hideLoading) {
      loadingInstance = Loading.service({
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.8)'
      });
    }

    return new Promise((resolve, reject) => {
      let config = {
        method: type || 'get',
        url: apiUrl,
        timeout: 1000,
        headers: {
          token: localStorage.nc_token || ''
        }
      };
      if (type == 'get') {
        // data.t = new Date().getTime();
        config.params = data;
      }
      if (type == 'post') config.data = data;
      Axios(config).then(res => {
        // console.log(res)
        setTimeout(() => {
          !hideLoading && loadingInstance.close();
        }, 200);

        if (res.data && res.data.status == '200') {
          resolve(res);
        } else {

          if (res.data.status === 800) {

            Message.error({
              message: '登录失效，即将返回登录页',
              type: 'error',
              duration: 1000,
              onClose: function(close) {
                // alert(locationUrl)
                // console.log(router)
                // window.location.href = locationUrl
                localStorage.clear()
                router.push('/')
                // return false
              }
            });


          }
          if (res.data.status === 500) {
            Message.error({
              message: '服务器异常,请检查操作！',
              type: 'error',
              duration: 1000
            });
            return
          }
          if (res.data.status === 400) {
            Message.error({
              message: res.data.body.message || res.data.body.msg,
              type: 'error',
              duration: 1000
            });

            return
          }
          if (res.data.code == 30000) {
            if (!!window.ActiveXObject || "ActiveXObject" in window) window.location.reload(); // ie
            return
          }
          Message.error({
            message: res.body.message
          });
        }

      }).catch(error => {
        setTimeout(() => {
          !hideLoading && loadingInstance.close();
        }, 200);
        // Message.error({ message: res.data.body.message });
      });
    });
  }
}
